package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.TransTypeEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.bo.TransFlowBO;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.service.UserBindService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.core.util.LendNoUtils;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.rabbitutil.service.MQService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author lwm
 * @since 2022-02-10
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Resource
    private UserInfoMapper userMapper;
    @Resource
    private TransFlowService transFlowService;
    @Resource
    private UserAccountService userAccountService;
    @Resource
    private UserBindService userBindService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private MQService mqService;

    //返回自动提交表单的html字符串
    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {
        //获取用户信息
        UserInfo userInfo = userMapper.selectById(userId);
        Map<String, Object> param = null;
        if (userInfo != null) {
            String bindCode = userInfo.getBindCode();
            //判断账户绑定状态
            Assert.notEmpty(bindCode, ResponseEnum.USER_NO_BIND_ERROR);
            //组装参数
            param = new HashMap<>();
            param.put("agentId", HfbConst.AGENT_ID);
            param.put("agentBillNo", LendNoUtils.getChargeNo());
            param.put("bindCode", bindCode);
            param.put("chargeAmt", chargeAmt);
            param.put("feeAmt", new BigDecimal("0"));
            param.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
            param.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
            param.put("timestamp", new Date().getTime());
            String sign = RequestHelper.getSign(param);
            param.put("sign", sign);
        }
        //构建充值自动提交表单的html字符串
        return FormHelper.buildForm(HfbConst.RECHARGE_URL, param);
    }

    //处理充值的异步回调
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notify(Map<String, Object> paramMap) {
        //幂等性判断，判断流水号是否已经存在
        String agentBillNo = (String) paramMap.get("agentBillNo");
        boolean exist = transFlowService.exist(agentBillNo);
        if (exist) {
            //已经处理过该笔交易，直接返回
            log.warn("幂等性返回");
            return;
        }
        //充值成功，同步用户的账户数据
        String bindCode = (String) paramMap.get("bindCode");
        BigDecimal chargeAmt = new BigDecimal((String) paramMap.get("chargeAmt"));
        boolean success = "0001".equals(paramMap.get("resultCode"));
        if (success) {
            //通过bindCode更新用户账户资金
            baseMapper.updateAccount(bindCode, chargeAmt, new BigDecimal(0));
            //记录交易流水
            TransFlowBO transFlowBO = new TransFlowBO();
            transFlowBO.setAgentBillNo(agentBillNo);
            transFlowBO.setBindCode(bindCode);
            transFlowBO.setAmount(chargeAmt);
            transFlowBO.setTransTypeEnum(TransTypeEnum.RECHARGE);
            transFlowBO.setMemo("用户充值，项目编号：" + agentBillNo);
            transFlowService.saveTransFlow(transFlowBO);

            //发消息
            log.info("发消息");
            String mobile = userInfoService.getMobileByBindCode(bindCode);
            SmsDTO smsDTO = new SmsDTO();
            smsDTO.setMobile(mobile);
            smsDTO.setMessage("充值成功");
            mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);
        }
    }

    //查询账户余额
    @Override
    public BigDecimal getAccount(Long userId) {
        LambdaQueryWrapper<UserAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAccount::getUserId,userId);
        UserAccount userAccount = baseMapper.selectOne(wrapper);
        BigDecimal balance = null;
        if (userAccount != null){
            balance = userAccount.getAmount();
        }
        return balance;
    }

    //生成用户提现提交表单
    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {
        //账户可用余额充足：当前用户的余额 >= 当前用户的提现金额
        BigDecimal amount = userAccountService.getAccount(userId);//获取当前用户的账户余额
        Assert.isTrue(amount.doubleValue() >= fetchAmt.doubleValue(),
                ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);


        String bindCode = userBindService.getBindCodeByUserId(userId);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getWithdrawNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("fetchAmt", fetchAmt);
        paramMap.put("feeAmt", new BigDecimal(0));
        paramMap.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建自动提交表单
        String formStr = FormHelper.buildForm(HfbConst.WITHDRAW_URL, paramMap);
        return formStr;
    }

    //处理异步回调的结果
    @Override
    public void notifyWithdraw(Map<String, Object> paramMap) {
        //幂等判断
        String agentBillNo = (String) paramMap.get("agentBillNo");
        boolean result = transFlowService.exist(agentBillNo);
        if (result) {
            log.warn("幂等性返回");
            return;
        }
        if("0001".equals(paramMap.get("resultCode"))) {
            log.info("提现成功");
            //拿到code和提现金额
            String bindCode = (String) paramMap.get("bindCode");
            String fetchAmt = (String) paramMap.get("fetchAmt");
            //同步账户金额
            baseMapper.updateAccount(bindCode, new BigDecimal("-" + fetchAmt), new BigDecimal(0));
            //增加提现的交易流水
            TransFlowBO transFlowBO = new TransFlowBO(
                    agentBillNo,
                    bindCode,
                    new BigDecimal(fetchAmt),
                    TransTypeEnum.WITHDRAW,
                    "提现");
            transFlowService.saveTransFlow(transFlowBO);
        }
    }
}
